package com.global.emc.spring.web.servlet.mvc.method.annotation;

import javax.servlet.http.HttpServletRequest;

import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;
import org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor;

import com.global.emc.spring.web.bind.annotation.ModelAndBody;

public class ModelAndBodyMethodProcessor implements HandlerMethodArgumentResolver{
	
	public ModelAndBodyMethodProcessor(RequestResponseBodyMethodProcessor requestResponseBodyMethodProcessor,ServletModelAttributeMethodProcessor servletModelAttributeMethodProcessor){
		this.requestResponseBodyMethodProcessor=requestResponseBodyMethodProcessor;
		this.servletModelAttributeMethodProcessor=servletModelAttributeMethodProcessor;
	}
	
	private RequestResponseBodyMethodProcessor requestResponseBodyMethodProcessor;
	private ServletModelAttributeMethodProcessor servletModelAttributeMethodProcessor;
	

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.hasParameterAnnotation(ModelAndBody.class);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter,ModelAndViewContainer mavContainer, NativeWebRequest webRequest,WebDataBinderFactory binderFactory) throws Exception {
		final HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
		HttpInputMessage inputMessage = new ServletServerHttpRequest(servletRequest);
		if(MediaType.APPLICATION_JSON.equals(inputMessage.getHeaders().getContentType())){
			return requestResponseBodyMethodProcessor.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
		}
		
		return servletModelAttributeMethodProcessor.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
	}

}
